package org.dreamfly.dreamalarm;

import java.util.List;

import org.dreamfly.dreamalarm.bean.Alarm;
import org.dreamfly.dreamalarm.inter.DeleteComponent;
import org.dreamfly.dreamalarm.inter.HandleComponent;
import org.dreamfly.dreamalarm.inter.ListComponent;
import org.dreamfly.dreamalarm.service.LocalService;
import org.dreamfly.dreamalarm.service.LocalService.LocalBinder;
import org.dreamfly.dreamalarm.service.WeiboService;
import org.dreamfly.dreamalarm.task.DeleteAsyncTask;
import org.dreamfly.dreamalarm.task.HandleAsyncTask;
import org.dreamfly.dreamalarm.task.ListAsyncTask;
import org.dreamfly.dreamalarm.util.ScaleFactory;
import org.dreamfly.dreamalarm.util.WeiboUtils;
import org.dreamfly.dreamalarm.util.db.DataBaseHelper;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

public class DreamAlarmActivity extends DreamAlarmFrameActivity implements
		HandleComponent, DeleteComponent, ListComponent, SensorEventListener {

	// -------------------------------------------------------------------------------
	// init
	// -------------------------------------------------------------------------------

	private DataBaseHelper dbHelper;

	Button newAlarmButton;
	ListView alarmListView;

	LocalService service;
	boolean mBound = false;

	// 定义sensor管理器
	private SensorManager mSensorManager;

	// 上次晃动 当前时间
	private long lastShakeTime = 0;
	private long currentTime = 0;
	// 记数器
	private int counter = 0;

	// 存储微博access_token,expire_in和isWeiboSharedOn
	public static final String SHAREPREFERENCE_DATA = "dream_alarm_sharepreference";

	// 微博分享是否开启
	protected boolean isWeiboSharedOn;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initApplication();
		MobclickAgent.onError(this);

		newAlarmButton = super.newAlarmButton;
		alarmListView = super.alarmListView;

		setListener();

		Intent intent = new Intent(DreamAlarmActivity.this, LocalService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

		// 获取传感器管理服务
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	}

	/**
	 * init all the attributes of application
	 */
	private void initApplication() {
		// init dbHelper
		DataBaseHelper.setContext(this);
		dbHelper = DataBaseHelper.getInstance();
		dbHelper.createDataBase();
		
		initWeibo();
		initScaleFactory();
	}
	
	private void initWeibo(){
		Editor sharedata = getSharedPreferences(
				DreamAlarmActivity.SHAREPREFERENCE_DATA, 0).edit();
		sharedata.putBoolean(AlertActivity.weibo_service_key, false);
		sharedata.putLong("weibo_id", 0);
		sharedata.commit();
		
		SharedPreferences sp = getSharedPreferences(SHAREPREFERENCE_DATA, 0);
		if (sp.getBoolean("isWeiboSharedOn", false) && !WeiboUtils.getInstance().isSessionValid(
				sp.getString("access_token", ""), sp.getLong("expires_in", 0))) {
			WeiboUtils.getInstance().goToAuthorize(this);
		}
	}
	
	private void initScaleFactory(){
		DisplayMetrics dm = new DisplayMetrics();
		dm = getApplicationContext().getResources().getDisplayMetrics();
		ScaleFactory.SCREEN_WIDTH = dm.widthPixels;
		ScaleFactory.SCREEN_HEIGHT = dm.heightPixels;
		ScaleFactory.x_Scaling = (float) ScaleFactory.SCREEN_WIDTH / ScaleFactory.DEFAULT_WIDTH;
		ScaleFactory.y_Scaling = (float) ScaleFactory.SCREEN_HEIGHT / ScaleFactory.DEFAULT_HEIGHT;
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (mBound) {
			unbindService(mConnection);
			mBound = false;
		}
		mSensorManager.unregisterListener(this);
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder iBinder) {
			// TODO Auto-generated method stub
			LocalBinder binder = (LocalBinder) iBinder;
			service = binder.getService();
			mBound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			service = null;
			mBound = false;
		}
	};

	// -------------------------------------------------------------------------------
	// 设置父类list相关抽象操作及事件处理
	// -------------------------------------------------------------------------------

	@Override
	void initListData() {
		list();
	}

	@Override
	void deleteButtonData(int id) {
		// TODO Auto-generated method stub
		delete(id);
	}

	@Override
	void checkBoxDataUpdate(int position, boolean open) {
		// TODO Auto-generated method stub
		handle(alarmListData.get(position), true);
	}

	private void setListener() {
		newAlarmButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (alarmListData.size() == Constants.MAXALARMNUM) {
					toast(R.string.toast_maxnum, true);
				} else {
					Intent intent = new Intent(DreamAlarmActivity.this,
							NewOrModifyAlarmActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.KEY_BETWEEN_ACTIVITY_METHOD,
							Constants.KEY_BETWEEN_ACTIVITY_METHOD_ADD);
					intent.putExtras(bundle);
					startActivityForResult(intent, NEW_ALARM_REQUEST);
				}
			}

		});

		alarmListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				// TODO Auto-generated method stub
				toUpdateId = position;

				Intent intent = new Intent(DreamAlarmActivity.this,
						NewOrModifyAlarmActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(Constants.KEY_BETWEEN_ACTIVITY_METHOD,
						Constants.KEY_BETWEEN_ACTIVITY_METHOD_MODIFY);
				bundle.putSerializable(Constants.KEY_BETWEEN_ACTIVITY_ALARM,
						alarmListData.get(toUpdateId));
				intent.putExtras(bundle);
				startActivityForResult(intent, NEW_ALARM_REQUEST);
			}

		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == NEW_ALARM_REQUEST) {
			if (resultCode == RESULT_OK) {
				handle((Alarm) data.getExtras().getSerializable(
						Constants.KEY_BETWEEN_ACTIVITY_ALARM), data.getExtras()
						.getBoolean(Constants.KEY_BETWEEN_ACTIVITY_TURNCHANGED));
			}
		}
	}

	// -------------------------------------------------------------------------------
	// 实现 Component接口
	// -------------------------------------------------------------------------------

	@Override
	public void handle(Alarm alarm, boolean turnChanged) {
		// TODO Auto-generated method stub
		HandleAsyncTask task = new HandleAsyncTask(this, this, alarm, false,
				turnChanged);
		task.execute();
	}

	@Override
	public void handleSuccessRefresh(boolean isAdd, Alarm alarm,
			boolean turnChanged) {
		// TODO Auto-generated method stub
		if (isAdd) {
			alarmListData.add(alarm);
			adapter.notifyDataSetChanged();
			if (alarm.getState() == Alarm.TURN_ON) {
				service.broadcastAlarm(alarm);
			}
		} else {
			alarmListData.set(toUpdateId, alarm);
			adapter.notifyDataSetChanged();

			if (turnChanged) {
				if (alarm.getState() == Alarm.TURN_ON) {
					service.broadcastAlarm(alarm);
				} else if (alarm.getState() == Alarm.TURN_OFF) {
					service.cancelAlarm(alarm.getId());
				}
			} else {
				if (alarm.getState() == Alarm.TURN_ON) {
					service.cancelAlarm(alarm.getId());
					service.broadcastAlarm(alarm);
				}
			}
		}
	}

	@Override
	public void handleErrorRefresh() {
		// TODO Auto-generated method stub
		toast(R.string.toast_dbwrong, true);
	}

	@Override
	public void delete(int id) {
		// TODO Auto-generated method stub
		DeleteAsyncTask task = new DeleteAsyncTask(this, this, id, false);
		task.execute();
	}

	@Override
	public void deleteSuccessRefresh(int id, boolean isTrunOn) {
		// TODO Auto-generated method stub
		if (isTrunOn) {
			service.cancelAlarm(id);
		}
	}

	@Override
	public void deleteErrorRefresh() {
		// TODO Auto-generated method stub
		toast(R.string.toast_dbwrong, true);
	}

	@Override
	public void list() {
		// TODO Auto-generated method stub
		ListAsyncTask task = new ListAsyncTask(this, this, false);
		task.execute();
	}

	@Override
	public void listSuccessRefresh(List<Alarm> list) {
		// TODO Auto-generated method stub
		alarmListData = list;
		adapter.notifyDataSetChanged();
	}

	@Override
	public void listErrorRefresh() {
		// TODO Auto-generated method stub

	}

	// ------------------------------------------------------------------------------
	// 处理menu
	//------------------------------------------------------------------------------
	private final int menu_itemid_havegetup=0;
	private final int menu_itemid_About=2;
	private final int menu_itemid_weibo=1;

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear(); // 清空目录
        menu.add(0, menu_itemid_havegetup, 0, R.string.mainframe_menu_havegetup).setIcon(
                android.R.drawable.ic_menu_myplaces);
        
        isWeiboSharedOn = getSharedPreferences(DreamAlarmActivity.SHAREPREFERENCE_DATA, 0).getBoolean("isWeiboSharedOn", false);
        if(isWeiboSharedOn){
			menu.add(0,menu_itemid_weibo,0,R.string.mainframe_menu_weibo_cancel).setIcon(
	        		android.R.drawable.ic_menu_share);
		}else{
			menu.add(0,menu_itemid_weibo,0,R.string.mainframe_menu_weibo_launch).setIcon(
	        		android.R.drawable.ic_menu_share);
		}
        
        menu.add(0, menu_itemid_About, 0, R.string.mainframe_menu_about).setIcon(
                android.R.drawable.ic_menu_help);
		
        return true;
	}

	/**
	 * 处理菜单的点击事件
	 * 
	 * @param menuItem
	 * @return
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem menuItem) {
		switch (menuItem.getItemId()) {
		case menu_itemid_havegetup:
			Builder builder = new AlertDialog.Builder(DreamAlarmActivity.this);
			builder.setTitle(this.getResources().getString(
					R.string.mainframe_dialog_havegetup_title));

			CharSequence[] items = { this.getResources().getString(
					R.string.mainframe_dialog_havegetup_choose_shake) };
			builder.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case 0:
						haveGetupWayOfShack();
						break;
					}}});
            	builder.show();
            	break;
		case menu_itemid_About:
			MobclickAgent.onEvent(this, Constants.YOUMENG_EVENT_ID_ABOUT);
        	Intent aboutIntent=new Intent(this,AboutActivity.class);
        	this.startActivity(aboutIntent);
        	break;
        case menu_itemid_weibo:    	
        	if(isWeiboSharedOn){
    			Editor sharedata = getSharedPreferences(DreamAlarmActivity.SHAREPREFERENCE_DATA, 0)
    					.edit();
    			sharedata.putBoolean("isWeiboSharedOn", false);
    			sharedata.commit();
    			WeiboService.shutDown=true;
    		}else{
    			MobclickAgent.onEvent(this, Constants.YOUMENT_EVENT_ID_WEIBOSET);
    			WeiboUtils.getInstance().goToAuthorize(DreamAlarmActivity.this);
    		}
        	break;
        }
        return true;
    }
	
    AlertDialog shackDialog;
    private void haveGetupWayOfShack(){
    	shackDialog=new AlertDialog.Builder(DreamAlarmActivity.this)
    	         .setMessage(R.string.mainframe_dialog_havegetup_shake_message)
    	         .create();
    	shackDialog.show();
    }
    
    private void haveGetupWayOfShackOff(){
    	shackDialog.dismiss();
    	shackDialog=null;
    	
    	for(Alarm alarm:alarmListData){
    		if(alarm.getType()==Alarm.TYPE_GETUP){
    			if(alarm.getWorkTimeDate().getTimeInMillis()>System.currentTimeMillis()
    			&& (alarm.getWorkTimeDate().getTimeInMillis()-1000*60*60<=System.currentTimeMillis())){
    				service.getUpEndAlarm(alarm);
    			}
    		}
    	}
    	
    	Intent i = new Intent("org.dreamfly.dreamfly.weiboservice");
    	this.stopService(i);
    }
    
    // ------------------------------------------------------------------------------
 	// 处理get up 1.加速传感器检测摇动手机
 	//------------------------------------------------------------------------------
    
    @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mSensorManager.unregisterListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 加速度传感器
		mSensorManager.registerListener(this,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				// 还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等，
				// 根据不同应用，需要的反应速率不同，具体根据实际情况设定
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	//
	
	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub

		if (shackDialog != null) {
			int sensorType = event.sensor.getType();

			// values[0]:X轴，values[0]：Y轴，values[0]：Z轴
			float[] values = event.values;

			if (sensorType == Sensor.TYPE_ACCELEROMETER) {
				currentTime = System.currentTimeMillis();
				if ((Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math
						.abs(values[2]) > 14)) {
					// 摇动手机后，设置button上显示的字为空
					if (currentTime - lastShakeTime > 200) {
						if (counter == 3) {
							// 执行一键起床
							haveGetupWayOfShackOff();
							counter = 0;
						} else {
							counter++;
						}
					}
					lastShakeTime = currentTime;
				}
			}
		}

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		// 当传感器精度改变时回调该方法，Do nothing.
	}

	// ------------------------------------------------------------------------------
	// tools
	// ------------------------------------------------------------------------------

	@Override
	void toast(int text, boolean longTime) {
		// TODO Auto-generated method stub
		if (longTime) {
			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
		}
	}

}
